package com.zui.webapp.support;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.HttpServletBean;

/**
 * 
 * @author Sam
 * @since 1.0
 */
public class DBInitServlet extends HttpServletBean {

	private static final long serialVersionUID = 1L;

	private String datasetLocation;
	private boolean enabled;

	@Override
	protected void initServletBean() throws ServletException {
		initDB();
	}

	/**
	 * database population with dbunit
	 * 
	 */
	@Override
	protected final void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		initDB();
		/**
		 * @TODO:wirte success response.
		 */

	}

	private void initDB() {
		if (!enabled)
			return;

		ApplicationContext ctx = WebApplicationContextUtils
				.getRequiredWebApplicationContext(this.getServletContext());
		if (datasetLocation == null)
			datasetLocation = XmlDataSetOperator.DEFAULT_DATASET_LOCATION;

		int dataSetCount = new XmlDataSetOperator(ctx, datasetLocation)
				.populateDataSet();
		if (logger.isDebugEnabled())
			logger.debug("Loaded " + dataSetCount
					+ " dataset xml files from location pattern ["
					+ datasetLocation + "]");
	}

	public void setDatasetLocation(String datasetLocation) {
		this.datasetLocation = datasetLocation;
	}

	public boolean isEnabled() {
		return enabled;
	}

	public void setEnabled(boolean enabled) {
		this.enabled = enabled;
	}

}
